<?php

namespace App\Http\Middleware;

use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\User;

class Authenticate
{
    /**
     * 处理请求
     */
    public function handle($request, Closure $next)
    {
        $token = $request->header('Authorization');
        
        if (!$token) {
            return response()->json([
                'code' => 401,
                'message' => '未授权访问，请先登录'
            ], 401);
        }
        
        // 移除Bearer前缀
        $token = str_replace('Bearer ', '', $token);
        
        try {
            // 验证token
            $decoded = JWT::decode($token, new Key(env('APP_KEY', 'default-key'), 'HS256'));
            $userId = $decoded->sub;
            
            // 查找用户
            $user = User::find($userId);
            
            if (!$user) {
                return response()->json([
                    'code' => 401,
                    'message' => '用户不存在'
                ], 401);
            }
            
            // 将用户信息存储到请求中
            $request->user = $user;
            
            return $next($request);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 401,
                'message' => '无效的令牌，请重新登录'
            ], 401);
        }
    }
}